package org.goodsmanager.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.goodsmanager.entity.Category;
import org.goodsmanager.entity.Product;
import org.goodsmanager.service.CategoryService;
import org.goodsmanager.service.ProductService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品搜索控制器
 */
@Slf4j
@Controller
@RequestMapping({"/search", "/shop/search"})
@RequiredArgsConstructor
public class SearchController {
    
    private final ProductService productService;
    private final CategoryService categoryService;
    
    /**
     * 搜索结果页面
     */
    @GetMapping({"", "/"})
    public String search(
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "12") int size,
            @RequestParam(required = false) String sortBy,
            @RequestParam(defaultValue = "desc") String sortOrder,
            @RequestParam(required = false) String categoryId,
            @RequestParam(required = false) Double minPrice,
            @RequestParam(required = false) Double maxPrice,
            @RequestParam(required = false) Integer status,
            Model model) {
        
        try {
            // 如果没有关键词，但有其他筛选条件，设置空字符串作为默认关键词
            if (keyword == null && (categoryId != null || minPrice != null || maxPrice != null)) {
                keyword = "";
            }
            
            // 如果没有任何搜索条件，重定向到首页
            if (keyword == null && categoryId == null && minPrice == null && maxPrice == null) {
                return "redirect:/shop";
            }
            
            // 获取所有分类
            List<Category> categories = categoryService.getActiveCategories();
            
            // 使用ProductService的分页查询方法
            Map<String, Object> searchResult;
            
            // 处理排序参数
            if (sortBy == null) {
                sortBy = "created_at";
                sortOrder = "desc";
            }
            
            searchResult = productService.getProductsByPage(page, size, keyword, categoryId, 
                    status, minPrice, maxPrice, sortBy, sortOrder);
            
            @SuppressWarnings("unchecked")
            List<Product> products = (List<Product>) searchResult.get("records");
            int total = (int) searchResult.get("total");
            int totalPages = (int) searchResult.get("totalPages");
            
            // 添加搜索建议（简单实现，实际项目中可以使用更复杂的算法）
            List<String> suggestions = generateSuggestions(keyword);
            
            model.addAttribute("products", products);
            model.addAttribute("keyword", keyword);
            model.addAttribute("currentPage", page);
            model.addAttribute("totalPages", totalPages);
            model.addAttribute("total", total);
            model.addAttribute("size", size);
            model.addAttribute("sortBy", sortBy);
            model.addAttribute("sortOrder", sortOrder);
            model.addAttribute("categoryId", categoryId);
            model.addAttribute("minPrice", minPrice);
            model.addAttribute("maxPrice", maxPrice);
            model.addAttribute("status", status);
            model.addAttribute("categories", categories);
            model.addAttribute("suggestions", suggestions);
            
            return "shop/search";
        } catch (Exception e) {
            log.error("搜索商品失败", e);
            model.addAttribute("error", "搜索失败，请稍后重试");
            return "shop/search";
        }
    }
    
    /**
     * 生成搜索建议
     */
    private List<String> generateSuggestions(String keyword) {
        // 简单实现，实际项目中可以使用更复杂的算法
        // 这里返回一些热门搜索关键词
        return List.of("手机", "电脑", "耳机", "键盘", "鼠标", "显示器", "笔记本", "平板");
    }
    
    /**
     * 搜索建议API
     */
    @GetMapping("/suggestions")
    @ResponseBody
    public Map<String, Object> getSuggestions(@RequestParam String keyword) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取商品名称建议
            List<String> productSuggestions = productService.getProductSuggestions(keyword, 5);
            
            // 获取热门搜索关键词
            List<String> hotKeywords = generateSuggestions(keyword);
            
            // 合并建议列表
            List<String> allSuggestions = new java.util.ArrayList<>();
            allSuggestions.addAll(productSuggestions);
            
            // 添加热门关键词（如果不在商品建议中）
            for (String hot : hotKeywords) {
                if (!allSuggestions.contains(hot) && allSuggestions.size() < 10) {
                    allSuggestions.add(hot);
                }
            }
            
            result.put("success", true);
            result.put("suggestions", allSuggestions);
        } catch (Exception e) {
            log.error("获取搜索建议失败", e);
            result.put("success", false);
            result.put("message", "获取搜索建议失败");
        }
        
        return result;
    }
}